package com.qing.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.qing.config.security.mapper.UsersMapper;
import com.qing.config.security.pojo.Users;
import com.qing.mapper.EmployeeMapper;
import com.qing.pojo.Employee;
import com.qing.pojo.EmployeeDetails;
import com.qing.pojo.EmployeeExcel;
import com.qing.service.EmployeeDetailsService;
import com.qing.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author qinghua
 * @date 2022/6/27 20:04
 */
@Slf4j
public class EmployeeListener implements ReadListener<EmployeeExcel> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 200;

    /**
     * 缓存的数据
     */
    private List<EmployeeExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private UsersMapper userMapper;

    private EmployeeMapper employeeMapper;

    private EmployeeDetailsService employeeDetailsService;

    private Map<String, Integer> deptMap;

    private Map<String, Integer> jobMap;

    public EmployeeListener(UsersMapper userMapper,
                            EmployeeMapper employeeMapper,
                            EmployeeDetailsService employeeDetailsService,
                            Map<String, Integer> deptMap,
                            Map<String, Integer> jobMap) {
        this.userMapper = userMapper;
        this.employeeMapper = employeeMapper;
        this.employeeDetailsService = employeeDetailsService;
        this.deptMap = deptMap;
        this.jobMap = jobMap;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(EmployeeExcel data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    /**
     * 加上存储数据库
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveData() {
        System.out.println(deptMap);
        System.out.println(jobMap);
        System.out.println(cachedDataList);
        cachedDataList.forEach(item -> {
            // 添加user表
            Users user = new Users();
            user.setUsername(item.getPhone());
            user.setPassword("123456");
            userMapper.insert(user);

            // employee表
            Employee employee = new Employee();
            employee.setUserId(user.getId());
            employee.setDeptId(deptMap.get(item.getDeptName()));
            employee.setJobId(jobMap.get(item.getJobName()));
            employee.setBaseSalary(item.getBaseSalary());
            employeeMapper.insert(employee);

            // employeeDetails表
            EmployeeDetails employeeDetails = new EmployeeDetails();
            employeeDetails.setEmployeeId(employee.getId());
            employeeDetails.setName(item.getEmployeeName());
            employeeDetails.setSex(item.getSex().equals("男") ? 1 : 2);
            employeeDetails.setPhone(item.getPhone());
            employeeDetails.setCardNum(item.getCardNum());
            employeeDetails.setEducation(item.getEducation());
            employeeDetails.setAddress(item.getAddress());
            employeeDetails.setPostCode(item.getPostCode());
            employeeDetails.setTel(item.getTel());
            employeeDetails.setQqNum(item.getQqNum());
            employeeDetails.setEmail(item.getEmail());
            employeeDetails.setParty(item.getParty());
            String birthday = item.getCardNum().substring(6, 10) + "-" + item.getCardNum().substring(10, 12) + "-" + item.getCardNum().substring(12, 14);
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
            Date date;
            try {
                date = ft.parse(birthday);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            employeeDetails.setBirthday(date);
            employeeDetails.setRace(item.getRace());
            employeeDetails.setSpeciality(item.getSpeciality());
            employeeDetails.setHobby(item.getHobby());
            employeeDetails.setRemake(item.getRemake());
            employeeDetailsService.save(employeeDetails);
        });

    }

}
